package com.xs.controller;

import com.xs.entity.Admin;
import com.xs.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@Controller
@RequestMapping("admin")
public class AdminController {

    @Autowired
    private AdminService adminService;

    /**
     * 登录
     * @param admin
     * @param httpSession
     * @return
     */
    @RequestMapping("login")
    public String login(Admin admin, HttpSession httpSession) {

        // 查询数据库
        Admin db_admin = adminService.login(admin);
        // 判断
        if (db_admin != null && db_admin.getAdminName() != null) {
            // 登录成功，放到session中
            httpSession.setAttribute("admin", db_admin);
            // 调用记录的方法（未写）

            return "redirect:/index.html";
        } else {
            return "redirect:/adminLogin.html";
        }
    }

    /**
     * 退出登录
     * @param request
     * @param response
     * @throws IOException
     */
    @RequestMapping("logout")
    public void logout(HttpServletRequest request, HttpServletResponse response) throws IOException {
    // session(false)
        HttpSession session = request.getSession(false);
        session.removeAttribute("admin");//移除数据
//         销毁session invalidate: 无效　使session失效
//        session.invalidate();

        response.sendRedirect(request.getContextPath() + "/adminLogin.html");
    }
}
